<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="$t('developer.operate_examine')"
    width="55%"
    @close="cancel"
  >
    <el-steps :active="active" align-center>
      <el-step :title="$t('operator.verify')" description="" />
      <el-step :title="$t('operator.process')" description="" />
      <el-step :title="$t('operator.checkComplete')" description="" />
    </el-steps>
    <div v-if="active === 1" class="stepContainer">
      <el-descriptions
        :title="$t('developer.developer_info')"
        direction="vertical"
        :column="4"
        border
        style="margin-top: 15px"
      >
        <el-descriptions-item
          v-if="developer.developerType === 1"
          :label="$t('developer.name')"
          >{{ developer.contactName }}</el-descriptions-item
        >
        <el-descriptions-item
          v-if="developer.developerType === 2"
          :label="$t('developer.company_name')"
          >{{ developer.firstName }}</el-descriptions-item
        >
        <el-descriptions-item :label="$t('developer.developerType')">
          <el-tag v-if="developer.developerType === 1" size="small">{{
            $t("developer.developer_type_list.personal")
          }}</el-tag>
          <el-tag v-if="developer.developerType === 2" size="small">{{
            $t("developer.developer_type_list.company")
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="developer.developerType === 1"
          :label="$t('developer.pidType')"
        >
          <el-tag v-if="developer.pidType === 1" size="small">{{
            $t("developer.id_card")
          }}</el-tag>
          <el-tag v-if="developer.pidType === 2" size="small">{{
            $t("developer.passport")
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item :label="$t('developer.email')">{{
          developer.email
        }}</el-descriptions-item>
        <el-descriptions-item :label="$t('developer.mobile')">{{
          developer.mobile
        }}</el-descriptions-item>
        <el-descriptions-item :label="$t('developer.pidNo')">{{
          developer.pidNo
        }}</el-descriptions-item>
        <el-descriptions-item :label="$t('developer.creTime')">{{
          formatDate(developer.creTime, "YYYY-MM-DD HH:mm:ss")
        }}</el-descriptions-item>
        <el-descriptions-item :label="$t('developer.status')">
          <el-tag v-if="developer.status === 2" size="small" type="warning">
            {{ statusFilter(developer.status) }}
          </el-tag>
          <el-tag v-if="developer.status === 1" size="small" type="success">
            {{ statusFilter(developer.status) }}
          </el-tag>
          <el-tag
            v-if="developer.status === 5 || developer.status === 7"
            size="small"
            type="info"
          >
            {{ statusFilter(developer.status) }}
          </el-tag>
          <el-tag
            v-if="
              developer.status === 0 || developer.status === 3 || developer.status === 8
            "
            size="small"
            type="danger"
          >
            {{ statusFilter(developer.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item :label="$t('developer.countryCode')">{{
          formatCountry(developer.countryCode)
        }}</el-descriptions-item>
        <el-descriptions-item :label="$t('developer.address')" :span="2">{{
          developer.address
        }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions
        :title="$t('developer.csr_info')"
        direction="vertical"
        :column="3"
        border
        style="margin-top: 15px"
      >
        <el-descriptions-item :label="$t('developer.common_name')">{{
          csr.cn
        }}</el-descriptions-item>
        <el-descriptions-item :label="$t('developer.province_name')">{{
          csr.provinceName
        }}</el-descriptions-item>
        <el-descriptions-item :label="$t('developer.locality_name')">{{
          csr.localityName
        }}</el-descriptions-item>
        <el-descriptions-item :label="$t('developer.organization_name')">{{
          csr.o
        }}</el-descriptions-item>
        <el-descriptions-item :label="$t('developer.organization_unit_name')">{{
          csr.ou
        }}</el-descriptions-item>
        <el-descriptions-item :label="$t('developer.sha_1')" :span="3">
          {{ csr.sha1 }}</el-descriptions-item
        >
        <el-descriptions-item :label="$t('developer.public_key')" :span="3">{{
          csr.pubKey
        }}</el-descriptions-item>
      </el-descriptions>
      <div
        style="
          border-top: 1px solid #edf2f9;
          padding-top: 10px;
          padding-right: 10px;
          text-align: right;
        "
      >
        <el-button type="danger" @click="rejectHandle">
          <svg-icon icon-class="Close" />
          {{ $t("operator.checkFailed") }}
        </el-button>
        <el-button type="primary" :disabled="this.nextStepVisible" @click="nextStep">
          <svg-icon icon-class="DArrowRight" />
          {{ $t("operator.checkSuccess") }}
        </el-button>
      </div>
    </div>
    <div v-if="active === 2 && !reject">
      <el-form
        ref="form"
        class="center"
        :model="form"
        :rules="dataRule"
        label-position="top"
      >
        <el-form-item :label="$t('common.remark')" required>
          <el-input
            v-model="form.remark"
            type="textarea"
            maxlength="256"
            :placeholder="$t('operator.checkSuccessTip')"
            :autosize="{ minRows: 4, maxRows: 10 }"
            @blur="() => (form.remark = form.remark.trim())"
          />
        </el-form-item>
        <div style="border-top: 1px solid #edf2f9; text-align: right">
          <el-upload
            ref="upload"
            action="#"
            accept=".crt"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :file-list="fileList"
            :auto-upload="false"
          >
            <!-- <template #trigger> -->
            <el-button type="primary">{{ $t("developer.btn_developer_cert") }}</el-button>
            <!-- </template> -->
            <el-button
              :disabled="this.fileList.length <= 0"
              type="success"
              :loading="uploadCerLoading"
              @click="submitUpload"
              ><svg-icon icon-class="Upload" />{{ $t("operator.uploadFile") }}</el-button
            >
            <el-button @click="preStep">{{ $t("common.back") }}</el-button>
          </el-upload>
        </div>
      </el-form>
    </div>
    <div v-if="active === 2 && reject" style="text-align: center">
      <el-form :model="form" :rules="dataRule" ref="ruleForm">
        <el-form-item prop="rejectionReason" class="center">
          <el-input
            v-model="form.rejectionReason"
            type="textarea"
            maxlength="256"
            show-word-limit
            :placeholder="$t('operator.checkFailedReasonTip')"
            :autosize="{ minRows: 4, maxRows: 10 }"
            @blur="() => (form.rejectionReason = form.rejectionReason.trim())"
          />
        </el-form-item>
      </el-form>
      <div
        style="
          border-top: 1px solid #edf2f9;
          padding-top: 10px;
          padding-right: 10px;
          text-align: right;
        "
      >
        <el-button v-show="this.backVisible" text @click="preStep">{{
          $t("common.back")
        }}</el-button>
        <el-button type="primary" :loading="rejectLoading" @click="rejectConfirm">{{
          $t("common.confirm")
        }}</el-button>
      </div>
    </div>
    <div v-if="active === 3" style="text-align: center; margin: 50px 0 50px 0">
      <span style="font-size: 25px; color: #5daf34; margin: 30%">
        {{ $t("operator.checkComplete") }}!
      </span>
    </div>
  </el-dialog>
</template>
<script>
import { checkDeveloper } from "@/api/developer";
import { formatDate } from "@/utils/formatDate";
import { formatCountry } from "@/utils/formatCountry";
import { getCsrInfo } from "@/api";

export default {
  data() {
    const validRemark = function (rule, file, cb) {
      if (this.form.remark.length < 1) {
        cb(new Error(this.$t("developer.error_tip.reject_remark")));
      } else {
        cb();
      }
    };
    const validRejectionReason = function (rule, file, cb) {
      if (this.form.rejectionReason.length < 1) {
        cb(new Error(this.$t("developer.error_tip.reject_remark")));
      } else {
        cb();
      }
    };
    return {
      rejectLoading: false,
      nextStepVisible: false,
      backVisible: true,
      reject: false,
      active: 1,
      fileList: [],
      developer: {},
      csr: {},
      form: {
        remark: "",
        rejectionReason: "",
      },
      uploadCerLoading: false,
      mapList: [],
      dataRule: {
        remark: [{ validator: validRemark.bind(this) }],
        rejectionReason: [{ validator: validRejectionReason.bind(this) }],
      },
    };
  },
  methods: {
    statusFilter(status) {
      const statusMap = {
        0: this.$t("developer.status_list.locked"),
        1: this.$t("developer.status_list.normal"),
        2: this.$t("developer.status_list.pending_review"),
        3: this.$t("developer.status_list.rejected"),
        5: this.$t("developer.status_list.country_examine"),
        7: this.$t("developer.status_list.cert_examine"),
        8: this.$t("developer.status_list.logged_off"),
      };
      return statusMap[status];
    },
    init(developer) {
      this.rejectLoading = false;
      this.developer = developer;
      this.form.remark = this.developer.remark;
      this.getCsrInfo(developer.developerId);
    },
    getCsrInfo(developerId) {
      getCsrInfo(developerId)
        .then((data) => {
          if (data) {
            this.csr = data;
            console.log(this.csr);
          }
        })
        .catch((err) => {
          this.$confirmError(err);
        });
    },
    formatCountry(value) {
      return formatCountry(value);
    },
    mapSelect() {
      this.form.mapKey = "";
    },
    cancel() {
      this.$emit("update:model-value", false);
    },
    nextStep() {
      this.active++;
    },
    preStep() {
      this.form.remark = this.developer.remark;
      this.form.rejectionReason = "";
      this.reject = false;
      this.active--;
    },
    rejectHandle(id) {
      this.reject = true;
      this.nextStep();
    },
    rejectConfirm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const formData = new FormData();
          formData.append("rejectionReason", this.form.rejectionReason);
          formData.append("examineStatus", 3);
          this.rejectLoading = true;

          checkDeveloper(this.developer.developerId, formData)
            .then((res) => {
              this.$message({
                type: "success",
                message: this.$t("operator.checkComplete"),
              });
              this.rejectLoading = false;
              this.$emit("refreshDataList");
              this.nextStep();
            })
            .catch((data) => {
              console.log(data);
              this.$message.error(data.message);
              this.fileList = [];
              this.rejectLoading = false;
              // http({
              //   method: 'POST',
              //   url: http.adornDeveloperAdminUrl(`/online/developer-admin/developer/${this.developer.developerId}/examine`),
              //   data: formData
              // }).then((res) => {
              //   this.$message({
              //     type: 'success',
              //     message: this.$t('operator.checkComplete')
              //   })
              //   this.rejectLoading = false
              //   this.$emit('refreshDataList')
              //   this.nextStep()
              // }).catch(data => {
              //   console.log(data.response.data)
              //   this.$message.error(data.response.data.message)
              //   this.fileList = []
              //   this.rejectLoading = false
              // })
            });
        }
      });
    },
    submitUpload() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.uploadCerLoading = true;
          const formData = new FormData();
          formData.append("file", this.fileList[0].raw);
          formData.append("remark", this.form.remark);
          formData.append("examineStatus", 1);
          checkDeveloper(this.developer.developerId, formData)
            .then((res) => {
              this.$message({
                type: "success",
                message: this.$t("operator.checkComplete"),
              });
              this.uploadCerLoading = false;
              this.$emit("refreshDataList");
              this.nextStep();
            })
            .catch((data) => {
              console.log(data);
              this.$message.error(data.message);
              this.fileList = [];
              this.uploadCerLoading = false;
            });
          // http({
          //   method: 'POST',
          //   url: http.adornDeveloperAdminUrl(`/online/developer-admin/developer/${this.developer.developerId}/examine`),
          //   data: formData
          // }).then((res) => {
          //   this.$message({
          //     type: 'success',
          //     message: this.$t('operator.checkComplete')
          //   })
          //   this.uploadCerLoading = false
          //   this.$emit('refreshDataList')
          //   this.nextStep()
          // }).catch(data => {
          //   console.log(data.response.data)
          //   this.$message.error(data.response.data.message)
          //   this.fileList = []
          //   this.uploadCerLoading = false
          // })
        }
      });
    },
    handleRemove(file, fileList) {
      fileList.shift();
    },
    handlePreview(file) {},
    handleChange: function (file, fileList) {
      if (fileList.length > 1) {
        fileList.shift();
      }
      this.fileList = fileList;

      var fileNameSplit = this.fileList[0].name.split(".");
      var suffix = fileNameSplit[fileNameSplit.length - 1];
      if (!(fileNameSplit.length === 2 && suffix === "crt")) {
        fileList.shift();
        this.$message.error("invalid file");
      }
    },
    formatDate(cellValue, fmt) {
      return formatDate(cellValue, fmt);
    },
  },
};
</script>
<style lang="scss" scoped>
.stepContainer {
  margin: 22px;
}

.center {
  width: 80%;
  margin: 15px 15% 15px 10%;
}
</style>
